﻿Public Class Main
  Private Sub Main_Load(Sender As Main, e As EventArgs) Handles MyBase.Load
    If My.Settings.InstallFolder.Trim = String.Empty Then
      My.Settings.InstallFolder = DEFAULT_INSTALL_FOLDER
    End If

    txtInstallFolder.Text = My.Settings.InstallFolder

    If Me.RunningProcesses.Count = 0 Then
      Me.StartFirefox()

    ElseIf Me.UnexpectedProcesses.Count = 0 Then
      Me.KillFirefox()

    End If
  End Sub



  Private Sub Main_FormClosing(Sender As Main, e As FormClosingEventArgs) Handles Me.FormClosing
    If Me.DialogResult = Windows.Forms.DialogResult.OK Then
      My.Settings.InstallFolder = txtInstallFolder.Text
    End If
  End Sub



  Private Sub txtFolder_TextChanged(Sender As TextBox, e As EventArgs) Handles txtInstallFolder.TextChanged
    cmdOk.Enabled = File.Exists(Me.InstallPath)
  End Sub



  Private Sub cmdSelect_Click(Sender As Button, e As EventArgs) Handles cmdSelect.Click
    If ofdSelect.ShowDialog = Windows.Forms.DialogResult.OK Then
      txtInstallFolder.Text = Path.GetDirectoryName(ofdSelect.FileName)
    End If
  End Sub



  Private Sub Button_Click(Sender As Button, e As EventArgs) Handles cmdOk.Click, cmdCancel.Click
    If Sender Is cmdOk Then KillFirefox()
    Me.Close()
  End Sub



  Private Sub KillFirefox()
    Me.RunningProcesses.ForEach(Sub(Process)
                                  Process.Kill()
                                  Process.WaitForExit()
                                End Sub)
    Me.StartFirefox()
  End Sub



  Private Sub StartFirefox()
    With Environment.GetCommandLineArgs.ToList
      Select Case .Count
        Case 1 : Process.Start(Me.InstallPath)
        Case 2 : Process.Start(Me.InstallPath, String.Format("-osint -url {0}", .Item(1)))
      End Select
    End With

    '"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -osint -url "%1"

    Me.Close(Windows.Forms.DialogResult.OK)
  End Sub



  Private ReadOnly Property UnexpectedProcesses As List(Of Process)
    Get
      Return Me.RunningProcesses.Where(Function(Process) Process.MainModule.FileName.ToLower <> Me.InstallPath.ToLower).ToList
    End Get
  End Property



  Private ReadOnly Property InstallPath As String
    Get
      Return Path.Combine(txtInstallFolder.Text, FILE_NAME)
    End Get
  End Property


  Private ReadOnly Property RunningProcesses As List(Of Process)
    Get
      Return _RunningProcesses
    End Get
  End Property
  Private ReadOnly _RunningProcesses As List(Of Process) = Process.GetProcessesByName(PROCESS_NAME).ToList



  Public Overloads Sub Close(Result As DialogResult)
    Me.DialogResult = Result
    Me.Close()
  End Sub



  Private Const DEFAULT_INSTALL_FOLDER As String = "C:\Program Files (x86)\Mozilla Firefox"
  Private Const PROCESS_NAME As String = "firefox"
  Private Const FILE_NAME As String = PROCESS_NAME & ".exe"
End Class
